using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Amba.System.Extensions;
using Amba.ULogin.Models;
using Amba.ULogin.Services;
using Orchard.ContentManagement;
using Orchard.Localization;

namespace Amba.ULogin.Controllers
{
    [ValidateInput(false)]
    public class ULoginController : AsyncController
    {
        private readonly IULoginService _uLoginService;
        private readonly IContentManager _contentManager;

        public ULoginController(IULoginService uLoginService, IContentManager contentManager)
        {
            _uLoginService = uLoginService;
            _contentManager = contentManager;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        [ValidateInput(false)]
        public ActionResult Login(string token, int partId = 0)
        {
            var webClient = new WebClient();
            var uloginResponse = webClient.DownloadString("http://u-login.com/token.php?token=" + token);
            var uLoginUser = new ULoginUser(uloginResponse);
            var user = _uLoginService.GetUserBySocial(uLoginUser);
            if (user == null)
            {
                user = _uLoginService.CreateUser(uLoginUser);
                if (partId > 0)
                {
                    var part = _contentManager.Get<ULoginPart>(partId);
                    if (part != null && !string.IsNullOrWhiteSpace(part.RolesForCreatedUsers))
                    {
                        var roleNames = part.RolesForCreatedUsers.FromJson<List<string>>();
                        _uLoginService.AddUserToRoles(user.Id, roleNames);
                    }
                }
            }
            else
            {
                _uLoginService.UpdateUserFieds(user, uLoginUser);
                _contentManager.Publish(user.ContentItem);
            }
            if (user == null)
            {
                return Json(new {Success = false});
            }
            _uLoginService.Logon(user, true);

            return Json(new {
                Success = true,
                User =  _uLoginService.ConverToPropertiesDictionary(user)
            });
        }
    }
}
